/**
 * [EventDispatcher description]
 */
export default class EventDispatcher {
  constructor() {}

  addEventListener(type, listener) {
    if (this.listeners === undefined) {
      this.listeners = {};
    }
    const listeners = this.listeners; // 更喜欢解构赋值
    if (listeners[type] === undefined) {
      listeners[type] = [];
    }
    if (listeners[type].indexOf(listener) === -1) {
      listeners[type].push(listener);
    }
  }

  hasEventListener(type, listener) {
    if (this.listeners === undefined) return false;
    const listeners = this.listeners;
    return listeners[type] !== undefined && listeners[type].indexOf(listener) !== -1;
  }

  removeEventListener(type, listener) {
    if (this.listeners === undefined) return;
    const listeners = this.listeners;
    const listenerArray = listeners[type];
    if (listenerArray !== undefined) {
      const index = listenerArray.indexOf(listener);
      if (index !== -1) {
        listenerArray.splice(index, 1);
      }
    }
  }

  dispatchEvent(event) {
    if (this.listeners === undefined) return;
    const listeners = this.listeners;
    const listenerArray = listeners[event.type];
    if (listenerArray !== undefined) {
      event.target = this;
      const array = listenerArray.slice(0);
      for (let i = 0, l = array.length; i < l; i++) {
        array[i].call(this, event);
      }
    }
  }

  toString() {
    return '';
  }
}